package xj.graph2d.app.prop;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Line2D;

import javax.swing.Icon;

import org.jvnet.flamingo.common.icon.ResizableIcon;

import xj.graph2d.DrawAttr;

public class CapIcon 
  implements ResizableIcon {

  static protected final Stroke simpleStroke = 
    new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);

  static protected final Stroke buttStroke = 
    new BasicStroke(9f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);

  static protected final Stroke roundStroke = 
    new BasicStroke(9f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);

  static protected final Stroke squareStroke = 
    new BasicStroke(9f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER);

  public CapIcon() {} 

  public CapIcon(int width, int height) { 
    this.width = width;
    this.height = height; 
  }

  protected int cap = DrawAttr.LINE_CAP_BUTT;

  protected int width = 16;
  protected int height = 16;
  protected Color bg = DrawAttr.defaultPenColor; //Color.black; 
  protected Color fg = Color.yellow; 

  public void setDimension(Dimension newDimension) {
    if (newDimension != null) { 
      width = newDimension.width; 
      height = newDimension.height; 
    }
  }

  public void setCapType(int cap) {
    this.cap = cap;
  }

  public int getCapType() {
    return cap;
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
			RenderingHints.VALUE_ANTIALIAS_ON);
    Shape clip = g2.getClip();
    g2.clipRect(x, y, width, height);
    Color oldColor = g2.getColor();
    Stroke oldStroke = g2.getStroke();

    g2.setColor(bg);
    switch (cap) {
    case DrawAttr.LINE_CAP_BUTT:
      g2.setStroke(buttStroke);
      break;
    case DrawAttr.LINE_CAP_ROUND:
      g2.setStroke(roundStroke);
      break;
    case DrawAttr.LINE_CAP_SQUARE:
      g2.setStroke(squareStroke);
      break;
    }
    y = y + (height - 1) / 2;
    g2.draw(new Line2D.Float(x, y, x + width / 2, y));
    g2.setColor(fg);
    g2.setStroke(simpleStroke);
    g2.draw(new Line2D.Float(x, y, x + width / 2, y));

    g2.setStroke(oldStroke);
    g2.setColor(oldColor);
    g2.setClip(clip);
  }

  public int getIconWidth() {
    return width;
  }

  public int getIconHeight() {
    return height;
  }

}
